package com.yangming.springboot.interceptors;

import com.yangming.springboot.exceptions.NoLoginException;
import com.yangming.springboot.service.UserService;
import com.yangming.springboot.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @创建人 ym
 * @创建时间 2021/3/15 0015
 * @描述 拦截器，拦截异常访问
 **/
public class NoLoginInterCeptor extends HandlerInterceptorAdapter {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        /*
        * 分析，获取cookies获取用户ID，
        * 如果id存在，切数据库查询成功，请求合法，
        * 反之用户未登陆为非法
        * */

        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        if (userId == 0 || userService.queryUserById(userId) == null){
           throw new NoLoginException();
        }

        return super.preHandle(request, response, handler);
    }

}
